/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package json;

import engine.Singleton;
import figure.Cross;
import figure.Round;
import server.ConnectClient;
import tictactoe.BeforeGame;
import tictactoe.EndGame;
import tictactoe.Offer;
import tictactoe.SmallField;
import tictactoe.UserComman;
import tictactoe.noGame;

/**
 *
 * @author Alexx
 */
public class ClientController implements IController
{
   ConnectClient connectClient;
 
  public ClientController (ConnectClient connectClient)
  {
    this.connectClient = connectClient;
  }

   @Override
  public void execute(String command, String name, String offerName, String row, String col)
  {
    if (command.equals("Users")){
     addUser(name);
    }
    if (command.equals("Offer")){
     offerUser(name);
    }
    if (command.equals("NoGame")){
     noGame();
    }
    if (command.equals("StartGame")){
     startGame(name, offerName);
    }
    if (command.equals("Step")){
     partnerStep(row, col);
    }
    if (command.equals("Finish")){
     finishGame(name);
    }
  } 
   
   public void finishGame(String status)
    {
      String end = "1";
      if (status.equals("win"))
        end = "Победил!";
      if (status.equals("lose"))
        end = "Проиграл!";
      if (status.equals("eq"))
        end = "Ничья!";
      
    new EndGame(end).setVisible(true);
    UserComman.clearField();
    }
    
    public void partnerStep(String row, String col)
    {
      int r = Integer.parseInt(row);
      int c = Integer.parseInt(col);
      connectClient.steps[r][c] = true;
      SmallField now = connectClient.matrix[r][c];
      if (connectClient.fig){
        now.add(new Round());
        now.repaint();
        connectClient.step = true;
      }
      else{
        now.add(new Cross());
        now.repaint();
        connectClient.step = true;
      }
      UserComman.disblock();
     
    }
    
    public void startGame(String figure, String step)
    {
      boolean fig = false;
      boolean fstep = false;
      if(figure.equals("Cross"))
        fig = true;
      if(step.equals("First"))
        fstep = true;
      UserComman.play(fig, fstep);
      new BeforeGame(fig, fstep).setVisible(true);
    }
    
    public void noGame()
    {
      new noGame().setVisible(true);
    }
    
    public void offerUser(String name)
    {
      new Offer(name).setVisible(true);
      connectClient.setPartner(name);
    }
    
    public void addUser(String name)
    {
      Singleton.Clientusers.clear();
      while (name.length() > 1)
      {
        int end = name.indexOf("-");
        String na = "";
        if (end > 0)
        {
          na = name.substring(0, end);
          name = name.substring(end + 1);
        } else
        {
          na = name;
          name = "";
        }
        Singleton.Clientusers.add(na);
        System.out.println("hh" + na);
      }
      UserComman.addUserToList();
    }
  
  
}
